﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SpotsHub.Tools.MassUploader
{
    public enum LogType
    {
        Information,
        Error
    }

    public class LogEntry
    {
        public LogType LogType { get; set; }
        public string Log { get; set; }
        public DateTime Time { get; set; }

        public override string ToString()
        {
            return String.Format("{0}\t{1}\t{2}\r\n", Time, LogType, Log);
        }
    }

    public class Logger
    {
        private object locker = new object();
        private static Logger _instance = new Logger();
        public static Logger Inst { get { return _instance; } }

        public bool Dirty;

        private Logger()
        {

        }

        private List<LogEntry> logEntries = new List<LogEntry>();

        public void Add(string log, params object[] args)
        {
            Add(LogType.Information, log, args);
        }

        public void Add(LogType type, string log, params object[] args)
        {
            lock (locker)
            {
                Dirty = true;
                logEntries.Add(new LogEntry() { LogType = type, Log = String.Format(log, args), Time = DateTime.Now });
            }
        }

        public void DumpToRichTextBox(RichTextBox rtb)
        {
            lock (locker)
            {
                rtb.Clear();
                foreach (var e in logEntries)
                {
                    string log = e.ToString();
                    int length = rtb.TextLength;  // at end of text
                    rtb.AppendText(log);
                    rtb.SelectionStart = length;
                    rtb.SelectionLength = log.Length;

                    switch (e.LogType)
                    {
                        case LogType.Information:
                            rtb.SelectionColor = Color.Black;
                            break;
                        case LogType.Error:
                            rtb.SelectionColor = Color.Red;
                            break;
                        default:
                            break;
                    }
                }

                Dirty = false;
                rtb.ScrollToCaret();
            }
        }

        public void DumpToDataGrid(DataGridView dgv)
        {
            lock (locker)
            {
                dgv.DataSource = logEntries;

                Dirty = false;
            }
        }
    }
}
